package com.kgc.controller;

import com.kgc.bean.GoodsItem;
import com.kgc.bean.HotWord;
import com.kgc.excpt.SysException;
import com.kgc.excpt.SysExceptionEnum;
import com.kgc.form.ElasticsearchGoodsResult;
import com.kgc.service.ElasticsearchService;
import com.kgc.util.ResultBuildUtil;
import com.kgc.util.ReturnResult;
import io.swagger.annotations.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * Created on 2021/6/21.
 * Author: lzy
 * Description:  分词搜索功能入口
 */
@RestController
@Api(tags = "首页搜索功能入口，包含热词检索,首页新品推送")
@Slf4j
public class ElasticsearchController {


    @Autowired
    private ElasticsearchService elasticsearchService;

    /**
     * @ClassName: ElasticsearchController
     * @Description 首页搜索功能
     * @Author lzy
     * @Date 2021/6/21
     */
    @GetMapping("/elasticsearch")
    @ApiOperation(value = "根据商品名称进行模糊查询", notes = "支持分词搜索，支持分页，支持统一返回")
    @ApiResponses({
            @ApiResponse(code = 3099, message = "ELASTICSEARCH连接失败"),
            @ApiResponse(code = 0000, message = "成功")
    })
    public ReturnResult<List<ElasticsearchGoodsResult>> toElasticSearchGoodsTitle(
            @ApiParam(required = true, name = "pageNo", value = "页码", defaultValue = "1") @RequestParam(required = false) Integer pageNo,
            @ApiParam(required = true, name = "pageSize", value = "每页容量", defaultValue = "10") @RequestParam(required = false) Integer pageSize,
            @ApiParam(required = true, name = "keyword", value = "搜索条件") @RequestParam String keyword) {

        // 先查询数据库是否存该热词
        if (!StringUtils.isEmpty(elasticsearchService.queryKeyWordIsHave(keyword).getId())) {
            // 将查询的热词保存到redis
            elasticsearchService.hotwordZincrby(keyword);
        }

        // 返回 查询的结果
        try {
            // 如果从elearch中未查找到数据，就去数据库里查询
            if (elasticsearchService.elsearchHighlightPage(keyword, pageNo, pageSize).size() > 0) {
                return ResultBuildUtil.success(elasticsearchService.elsearchHighlightPage(keyword, pageNo, pageSize));
            } else {
                // 去数据库查询
                if (!ObjectUtils.isEmpty(elasticsearchService.querySelectGoodsItemByKeyword(keyword, pageNo, pageSize))) {
                    elasticsearchService.saveGoodsItemToElasticsearch(elasticsearchService.querySelectGoodsItemByKeyword(keyword, pageNo, pageSize));
                }
                return ResultBuildUtil.success(elasticsearchService.querySelectGoodsItemByKeyword(keyword, pageNo, pageSize));
            }
        } catch (IOException e) {
            log.info("根据商品名称模糊查询产生异常，异常为：{}", e.getMessage());
            throw new SysException(SysExceptionEnum.ELASTICSEARCH_CONNECT_EXCPT);
        }
    }


    /**
     * @ClassName: ElasticsearchController
     * @Description 前端获取热词
     * @Author lzy
     * @Date 2021/6/22
     */
    @GetMapping("/hotwordshow")
    @ApiOperation(value = "展示热词", notes = "每次展示5条热词数据")
    @ApiResponses({
            @ApiResponse(code = 2002, message = "查询热词失败"),
            @ApiResponse(code = 0000, message = "成功")
    })
    public ReturnResult<List<HotWord>> queryHotWord() {
        List<HotWord> data = new ArrayList<>();
        data = elasticsearchService.querySelectHotWord5();
        if (data.size() != 0) {
            return ResultBuildUtil.success(data);
        } else {
            return ResultBuildUtil.fail("2002", "查询失败");
        }

    }

    //首页新品推送功能
    @GetMapping("/newProductPush")
    @ApiOperation(value = "新品推送", notes = "推送五个新品")
    public ReturnResult<List<GoodsItem>> newProductPush() {
        List<GoodsItem> data = new ArrayList<>();

        if (elasticsearchService.queryNewProduct().size() <= 0) {
            //如果查询到的新品集合为空
            return ResultBuildUtil.fail("2100", "当日无新品");
        } else {
            if (elasticsearchService.queryNewProduct().size() <= 5) {
                //如果新品查询不足五个，展示所有查询到的新品信息
                data = elasticsearchService.queryNewProduct();
            } else {
                //如果查询到的新品超过五个，则取集合前五个展示
                data = elasticsearchService.queryNewProduct().subList(0, 4);
            }
        }

        return ResultBuildUtil.success(data);
    }


}
